<?php
//=======================================
//###################################
// Kayako Web Solutions
//
// Source Copyright 2001-2004 Kayako Web Solutions
// Unauthorized reproduction is not allowed
// License Number: $%LICENSE%$
// $Author: rclark $ ($Date: 2007/07/19 22:33:16 $)
// $RCSfile: impex.tickets.php,v $ : $Revision: 1.5 $ 
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//
//###################################
//=======================================

if (!defined("INSWIFT")) {
	trigger_error("Unable to process $PHP_SELF", E_USER_ERROR);
}

require_once ("./modules/tickets/tickets.php");

/**
* Return the Total Pages for this Plugin
*/
function getPluginTotalPages1()
{
	global $impexDB;

	$_total = $impexDB->queryFetch("SELECT COUNT(*) AS totaltickets FROM `tt_ticket`;");
	$finaltotal = intval($_total["totaltickets"]);

	$totalpages = ceil($finaltotal/IMPEX_PASS)+1;

	return $totalpages;
}

/**
* Run the specific page for plugin
*/
function runPluginPage1($page)
{
	global $dbCore, $impexDB, $_IMPEXHASH, $_SWIFT;

	// Import Predefined Replies
	if ($page == 1)
	{
		$predefinedcategoryid = _impexInsertPredefinedCategory(0, "SupportTrio Impex");

		$predefinedreplies = array();
		$impexDB->query("SELECT * FROM `tt_can_response` ORDER BY `id` ASC;");
		while ($impexDB->nextRecord())
		{
			$predefinedreplies[$impexDB->Record["id"]] = $impexDB->Record;
		}

		foreach ($predefinedreplies as $key=>$val)
		{
			_impexInsertPredefinedReply($predefinedcategoryid, $val["title"], $val["contents"]);

			displayStatus("Imported Predefined Reply: ".htmlspecialchars($val["title"]));
		}

	// Import Tickets
	} else {
		// Import Tickets! The big tough crap function.
		if (empty($_POST["ticketstartat"]))
		{
			$_startat = 1;
		} else {
			$_startat = intval($_POST["ticketstartat"]);
		}

		$ticketidlist = $ticketlist = $ticketidcharlist = $ticketidpointer = $newticketpointer = array();

		// First get all the tickets
		$impexDB->query("SELECT * FROM `tt_ticket` WHERE `id` >= '". intval($_startat) ."' ORDER BY `id` ASC LIMIT ". intval(IMPEX_PASS) .";");
		while ($impexDB->nextRecord())
		{
			_impexProcessSlashVariables($impexDB->Record);

			$ticketidlist[] = $impexDB->Record["id"];
			$ticketidcharlist[] = $impexDB->Record["id"];
			$ticketidpointer[$impexDB->Record["id"]] = $impexDB->Record["id"];
			$ticketlist[$impexDB->Record["id"]] = $impexDB->Record;
			$ticketlist[$impexDB->Record["id"]]["posts"] = array();
			$lastticketid = $impexDB->Record["id"];
		}

		// Now load in stuff from asTicketReply table
		$impexDB->query("SELECT * FROM `tt_ticket_dat` WHERE `par_id` IN (". buildIN($ticketidlist) .");");
		while ($impexDB->nextRecord())
		{
			_impexProcessSlashVariables($impexDB->Record);

			$ticketidno = intval($ticketidpointer[$impexDB->Record["par_id"]]);
			$_ticket = &$ticketlist[$ticketidno];

			if (count($_ticket["posts"]) == 0)
			{
				$_updatetticket = true;
			} else {
				$_updatetticket = false;
			}

			$_ticket["posts"][$impexDB->Record["id"]] = $impexDB->Record;
			$_ticket["posts"][$impexDB->Record["id"]]["dateline"] = returnSupportTrioTimestamp($impexDB->Record["date"], $impexDB->Record["time"]);

			if (!empty($impexDB->Record["adminid"]))
			{
				// Is Staff
				$_fullname = $_IMPEXHASH["staffnamepointer"][$impexDB->Record["adminid"]];
				$_email = $_IMPEXHASH["staffemailpointer"][$impexDB->Record["adminid"]];
				$_creator = "staff";
			} else {
				$_fullname = $_email = $_ticket["cemail"];
				$_creator = "customer";
			}

			if (empty($_fullname) || empty($_email))
			{
				$_fullname = $_email = $_ticket["cemail"];
				$_creator = "customer";
			}

			if ($_updatetticket == true)
			{
				$_ticket["subject"] = $impexDB->Record["subject"];
				$_ticket["fullname"] = $impexDB->Record["fullname"];
				$_ticket["email"] = $impexDB->Record["email"];
			}

			$_ticket["posts"][$impexDB->Record["id"]]["fullname"] = $_fullname;
			$_ticket["posts"][$impexDB->Record["id"]]["email"] = $_email;
			$_ticket["posts"][$impexDB->Record["id"]]["subject"] = $impexDB->Record["subject"];
			$_ticket["posts"][$impexDB->Record["id"]]["creator"] = $_creator;
			$_ticket["posts"][$impexDB->Record["id"]]["contents"] = urldecode($impexDB->Record["content"]);
		}

		// By now, almost all data should be loaded.. insert the tickets first
		foreach ($ticketlist as $key=>$val)
		{
			$newdepartmentid = intval($_IMPEXHASH["departmentpointer"][$val["cat"]]);
			if (empty($newdepartmentid))
			{
				displayStatus("<font color='red'>WARNING:</font> Ticket ".$val["id"]." does not have a valid department. Ignoring.");
			} else {
				$ticketid = _impexInsertTicket(generateTicketMask(), $newdepartmentid, intval($val["level"]), 1, "0", "0", "0", "0", $val["fullname"], $val["email"], $val["fullname"], $val["subject"], returnSupportTrioTimestamp($val["date"]), returnSupportTrioTimestamp($val["l_date"]), count($val["posts"]), POST_CLIENT);

				$firstpostid = $lastpostid = 0;

				foreach ($val["posts"] as $postkey=>$postval)
				{
					$_ticketpostid = _impexInsertTicketPost($ticketid, $postval["dateline"], "0", $postval["fullname"], $postval["email"], "", $postval["subject"], "", iif($postval["creator"]=="customer", POST_CLIENT, POST_STAFF), 0, 0, $postval["contents"]);
					$lastreplier = $postval["fullname"];
					if (empty($firstpostid))
					{
						$firstpostid = $_ticketpostid;
					}
					$lastpostid = $_ticketpostid;
				}

				$dbCore->query("UPDATE `". TABLE_PREFIX ."tickets` SET `lastreplier` = '". $dbCore->escape(iif(empty($lastreplier), $val["fullname"], $lastreplier)) ."', `firstpostid` = '". intval($firstpostid) ."', `lastpostid` = '". intval($lastpostid) ."' WHERE `ticketid` = '". intval($ticketid) ."';");
				$newticketpointer[$val["id"]] = $ticketid;

				displayStatus("Imported Ticket: #".$val["id"]);
			}
		}

		unset($ticketlist);

		$_SWIFT["ticketstartat"] = $lastticketid+1;
	}
}

/**
* Generate a random Ticket Mask
*/
function generateTicketMask()
{
	global $_SWIFT;

	mt_srand ((double) microtime() * 1000000);
	$alpha1 = mt_rand(65,90);
	mt_srand ((double) microtime() * 1000000);
	$alpha2 = mt_rand(65,90);
	mt_srand ((double) microtime() * 1000000);
	$alpha3 = mt_rand(65,90);

	$alpha1 = chr($alpha1);
	$alpha2 = chr($alpha2);
	$alpha3 = chr($alpha3);

	// This was a serious issue in v2, The stupid computer would come up with words like GAY and client would be pissed as hell.
	$prefix = $alpha1.$alpha2.$alpha3;
	if (in_array(strtoupper($prefix), $_SWIFT["stopwords"]))
	{
		return generateTicketMask();
	}

	mt_srand ((double) microtime() * 1000000);
	$num = mt_rand(100000,999999);
	$ticketmaskid = $alpha1 . $alpha2 . $alpha3 . "-" . $num;

	return $ticketmaskid;
}
?>